package com.example.learnandroid;

import java.io.FileOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.churnlabs.ffmpegsample.MainActivity;
import com.stay.gif.GifEncoder;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MakeGIF extends Activity {
	private Button step1,step2,test;
	final static int REQUEST_VIDEO_CAPTURED = 1;
	Uri uriVideo = null;
	private Bitmap mBitmap;
	private static int filenum = 1;
	private ArrayList<Bitmap> lBitmap;
	private Bitmap arrBitmap[];
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.makegif);
		
		addListenerOnButton();
	}
	
	
	public void addListenerOnButton() {
		step1 = (Button) findViewById(R.id.takevideo);
		step2 = (Button) findViewById(R.id.extract);
		test = (Button) findViewById(R.id.test);
		step1.setOnClickListener(new OnClickListener() {
 
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
				startActivityForResult(intent, REQUEST_VIDEO_CAPTURED);
			}

			
		});
		
		step2.setOnClickListener(new OnClickListener() {
			 
			@Override
			public void onClick(View arg0) {
				String pathVideo = getRealPathFromURI(uriVideo);	
				if(pathVideo==null){
					Log.e("TAG","path video null");
					return;
				}
				int width = 420;
				int height = 280;
				MainActivity ffmpeg = new MainActivity();
				ffmpeg.openFile(pathVideo);
				GifEncoder giflen = new GifEncoder();
				int state =	giflen.init("/sdcard/gif/output.gif", width, height, 256, 50, 20);
				if (state != 0) {
					Log.e("TAG","Init gifflen error");
					return;
				}
				int [] pixels = new int[width * height];
				
				mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test2 );
				int mSecs = 0;
				
				
				 
				
				
				try{
					/*for(int i=0;i<20;i++){
						MainActivity.drawFrameAt(mBitmap, mSecs ,width, height);
						mBitmap.getPixels(pixels, 0, width, 0, 0, width, height);
						giflen.addFrame(pixels);
						mSecs +=200;

						FileOutputStream out = new FileOutputStream("/sdcard/bitmap/"+String.valueOf(i+1)+".jpg");
						mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
						mBitmap.recycle();
					}
					*/
					
					
				}catch(Exception e){
					
				}
				giflen.close();
				Toast.makeText(MakeGIF.this,"Yeah!",Toast.LENGTH_LONG)
						.show();
			}

			
		});
		
		test.setOnClickListener(new OnClickListener() {
			 
//			@Override
//			public void onClick(View arg0) {
//				try{
//					ArrayList<Bitmap> arr_bitmap = getFrames("/sdcard/baby.mp4");
//					for(int i=0;i< arr_bitmap.size();i++){
//						FileOutputStream out = new FileOutputStream("/sdcard/bitmap/"+String.valueOf(i+1)+".jpg");
//						arr_bitmap.get(i).compress(Bitmap.CompressFormat.JPEG, 100, out);
//						Log.i("TAG","frame " + String.valueOf(i));
//					}
//				}catch(Exception e){
//					
//				}
//			}

			@Override
			public void onClick(View arg0) {
				try{
					long start = System.currentTimeMillis();
					int width = 320;
					int height = 240;
					
					// extract video to bitmap
					MainActivity ffmpeg = new MainActivity();
					ffmpeg.openFile("/sdcard/myvideo.mp4");
					mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test0 );
					lBitmap = new ArrayList<Bitmap>();
					
					for(int i=0;i<200;i++){
						if(i%10==0){
							//Bitmap bm = getBitMapById(i/10);
							Bitmap bm = mBitmap.copy(Bitmap.Config.ARGB_8888, true);
							ffmpeg.drawFrame(bm ,width, height,1);
							lBitmap.add(bm);
							//bm.getPixels(pixels, 0, width, 0, 0, width, height);
							//giflen.addFrame(pixels);
							//FileOutputStream out = new FileOutputStream("/sdcard/bitmap/"+String.valueOf(i+1)+".jpg");
							//mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
							//Log.i("TAG","frame " + String.valueOf(i));
						}
						else{
							ffmpeg.drawFrame(mBitmap ,width, height,0);
						}
						
					}
					Intent intent = new Intent(MakeGIF.this, PreviewGIF.class);
					//DataSend data = new DataSend();
					//data.lBitmap = lBitmap;
            		//intent.putExtra("listImage",data);
            		//intent.putParcelableArrayListExtra("images", lBitmap);
					
					//intent.putExtra("images", mBitmap);
					Images.listImage = lBitmap;
                    startActivity(intent);
                    
					// make gif
					/*GifEncoder giflen = new GifEncoder();
					int state =	giflen.init("/sdcard/gif/output.gif", width, height, 256, 10, 20);
					if (state != 0) {
						Log.e("TAG","Init gifflen error");
						return;
					}
					int [] pixels = new int[width * height];
					for(int i=0;i<lBitmap.size();i++){
						lBitmap.get(i).getPixels(pixels, 0, width, 0, 0, width, height);
						giflen.addFrame(pixels);
					}
					giflen.close();*/
					
					long stop = System.currentTimeMillis();
					System.out.println(stop-start);
					
				}catch(Exception e){
					System.out.println(e.getMessage());
				}
			}
		});
		
 
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(resultCode == RESULT_OK){
			if(requestCode == REQUEST_VIDEO_CAPTURED){
				uriVideo = data.getData();
				Toast.makeText(MakeGIF.this, 
						getRealPathFromURI(uriVideo), 
						Toast.LENGTH_LONG)
						.show();
			}
		}else if(resultCode == RESULT_CANCELED){
			uriVideo = null;
			Toast.makeText(MakeGIF.this, 
					"Cancelled!", 
					Toast.LENGTH_LONG)
					.show();
		}
	}
	
	public String getRealPathFromURI(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String path = cursor.getString(column_index);
        return path.substring(4, path.length());
    }
	
	private ArrayList<Bitmap> getFrames(String path) {
	    try {
	        ArrayList<Bitmap> bArray = new ArrayList<Bitmap>();
	        bArray.clear();
	        MediaMetadataRetriever mRetriever = new MediaMetadataRetriever();
	        mRetriever.setDataSource(path);                    

	        for (int i = 0; i < 100; i++) {
	            bArray.add(mRetriever.getFrameAtTime(1000000*i, 
	                       MediaMetadataRetriever.OPTION_CLOSEST));
	        }
	        return bArray;
	    } catch (Exception e) { return null; }
	}
	
	
}
